package bo;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.oreilly.servlet.ServletUtils;

import jxl.read.biff.BiffException;
import jxl.write.WriteException;

/**
 * Servlet implementation class DownLoad
 */
@WebServlet("/DownLoad")
public class DownLoad extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownLoad() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String filepath=this.getServletContext().getRealPath("");//下载的文件所处路径
		String filename="card.xls";//要下载的文件名字
		
		HttpSession session=request.getSession();
		List<book> list = (List<book>)session.getAttribute("list");
		File file=new File(filepath+"/"+filename);
		try {
			book.ExportExcel(file, list);
		} catch (BiffException | WriteException | ClassNotFoundException
				| SQLException e1) {
			e1.printStackTrace();
		}
		
		String guessCharset="UTF-8";
		try{
			String isofilename=new String(filename.getBytes(guessCharset),"iso-8859-1");
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition","attachment;filename="+isofilename);
			ServletOutputStream out=null;
			out=response.getOutputStream();
			ServletUtils.returnFile(filepath+"/"+filename, out);
		}catch(UnsupportedEncodingException ex){
			ex.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}
